import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Lightbulb, Clock, Trophy, Star, AlertTriangle, X } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';
import { CriticalThinkingQuestion } from '../types/criticalThinking';
import { CRITICAL_THINKING_POOL } from '../constants/criticalThinking';

interface CriticalThinkingTestProps {
  onComplete: (result: TestResult) => void;
}

export function CriticalThinkingTest({ onComplete }: CriticalThinkingTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [selectedQuestions, setSelectedQuestions] = useState<CriticalThinkingQuestion[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(900); // 15分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [feedbackExplanation, setFeedbackExplanation] = useState('');

  const QUESTIONS_PER_TEST = 12;

  // 随机选择题目
  const selectRandomQuestions = () => {
    const shuffled = [...CRITICAL_THINKING_POOL].sort(() => Math.random() - 0.5);
    
    // 确保每种类型都有代表
    const questionsByType: { [key: string]: CriticalThinkingQuestion[] } = {
      assumption: [],
      argument_evaluation: [],
      logical_fallacy: [],
      cause_effect: [],
      inference: [],
      bias_detection: []
    };
    
    // 按类型分组
    shuffled.forEach(q => {
      if (questionsByType[q.type].length < 2) {
        questionsByType[q.type].push(q);
      }
    });
    
    // 收集选中的题目
    const selected: CriticalThinkingQuestion[] = [];
    Object.values(questionsByType).forEach(typeQuestions => {
      selected.push(...typeQuestions);
    });
    
    // 如果不够12道，随机补充
    if (selected.length < QUESTIONS_PER_TEST) {
      const remaining = shuffled.filter(q => !selected.includes(q));
      const needed = QUESTIONS_PER_TEST - selected.length;
      selected.push(...remaining.slice(0, needed));
    }
    
    return selected.sort(() => Math.random() - 0.5).slice(0, QUESTIONS_PER_TEST);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    const questions = selectRandomQuestions();
    setSelectedQuestions(questions);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleAnswer = (answerIndex: number) => {
    const question = selectedQuestions[currentQuestion];
    const correct = answerIndex === question.correct;
    
    setResponses(prev => [...prev, answerIndex]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }
    
    // 显示反馈
    setFeedbackCorrect(correct);
    setFeedbackExplanation(question.explanation);
    setShowFeedback(true);
  };

  const handleCloseFeedback = () => {
    setShowFeedback(false);
    
    if (currentQuestion < selectedQuestions.length - 1) {
      setCurrentQuestion(prev => prev + 1);
    } else {
      setStage('results');
    }
  };

  const handleComplete = () => {
    const totalQuestions = selectedQuestions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 按题目类型统计
    const typeStats: { [key: string]: { correct: number; total: number } } = {};
    
    selectedQuestions.forEach((question, index) => {
      const type = question.type;
      if (!typeStats[type]) {
        typeStats[type] = { correct: 0, total: 0 };
      }
      typeStats[type].total++;
      if (responses[index] === question.correct) {
        typeStats[type].correct++;
      }
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'critical-thinking',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalQuestions,
        correctAnswers,
        accuracy,
        averageTimePerQuestion: Math.round(timeUsed / totalQuestions),
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type: type === 'assumption' ? '假设识别' :
                type === 'argument_evaluation' ? '论证评估' :
                type === 'logical_fallacy' ? '逻辑谬误' :
                type === 'cause_effect' ? '因果推理' :
                type === 'inference' ? '合理推断' : '偏误检测',
          accuracy: stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
          correct: stats.correct,
          total: stats.total
        })),
        questionsUsed: selectedQuestions.map(q => q.id),
        contexts: selectedQuestions.map(q => q.context)
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-yellow-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Lightbulb className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">批判性思维测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的逻辑分析和批判性思维能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-yellow-50 to-orange-50 rounded-xl p-6 border border-yellow-100">
              <h3 className="font-semibold text-yellow-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-yellow-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>分析现实生活中的论证和推理场景</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-yellow-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>识别逻辑谬误、认知偏误和不合理假设</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-yellow-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>评估论证的有效性和推理的合理性</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-yellow-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>每次测试从20+道题中随机选择12道</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-red-50 to-red-100 rounded-xl p-4 border border-red-200">
                <h4 className="font-semibold text-red-800 mb-2 flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  逻辑谬误
                </h4>
                <p className="text-sm text-red-700">识别推理中的逻辑错误</p>
              </div>
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2">论证评估</h4>
                <p className="text-sm text-blue-700">分析论证的强度和有效性</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-xl border border-yellow-200">
                <div className="text-2xl font-bold text-yellow-600 mb-1">20+</div>
                <div className="text-sm text-yellow-700">题库数量</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">12</div>
                <div className="text-sm text-orange-700">随机题目</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-yellow-50 to-orange-50 rounded-xl border border-yellow-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">15</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-yellow-600 to-orange-500 hover:from-yellow-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && selectedQuestions.length > 0) {
    const question = selectedQuestions[currentQuestion];
    const progress = (currentQuestion / selectedQuestions.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-yellow-100 text-yellow-700 border-yellow-300">
              题目 {currentQuestion + 1} / {selectedQuestions.length}
            </Badge>
            <Badge variant="outline" className={`${
              question.type === 'assumption' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              question.type === 'argument_evaluation' ? 'bg-green-100 text-green-700 border-green-300' :
              question.type === 'logical_fallacy' ? 'bg-red-100 text-red-700 border-red-300' :
              question.type === 'cause_effect' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              question.type === 'inference' ? 'bg-indigo-100 text-indigo-700 border-indigo-300' :
              'bg-orange-100 text-orange-700 border-orange-300'
            }`}>
              {question.type === 'assumption' ? '假设识别' :
               question.type === 'argument_evaluation' ? '论证评估' :
               question.type === 'logical_fallacy' ? '逻辑谬误' :
               question.type === 'cause_effect' ? '因果推理' :
               question.type === 'inference' ? '合理推断' : '偏误检测'}
            </Badge>
            <Badge variant="outline" className={`${
              question.difficulty === 'easy' ? 'bg-green-100 text-green-700 border-green-300' :
              question.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              'bg-red-100 text-red-700 border-red-300'
            }`}>
              {question.difficulty === 'easy' ? '简单' :
               question.difficulty === 'medium' ? '中等' : '困难'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 120 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 场景卡片 */}
        <Card className="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200">
          <CardHeader>
            <div className="flex items-center gap-2 mb-2">
              <Badge variant="secondary" className="text-xs">
                {question.context}
              </Badge>
            </div>
            <CardTitle className="text-lg text-slate-800">场景分析</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-slate-700 leading-relaxed text-base italic">
              "{question.scenario}"
            </p>
          </CardContent>
        </Card>

        {/* 问题区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-xl text-slate-800">{question.question}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {question.options.map((option, index) => (
              <motion.div
                key={index}
                whileHover={{ scale: 1.01 }}
                whileTap={{ scale: 0.99 }}
              >
                <Button
                  variant="outline"
                  onClick={() => handleAnswer(index)}
                  disabled={showFeedback}
                  className="w-full h-auto min-h-[3rem] text-left justify-start p-4 hover:bg-yellow-50 hover:border-yellow-300 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <div className="flex items-center gap-3">
                    <span className="w-8 h-8 bg-yellow-100 text-yellow-700 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0">
                      {String.fromCharCode(65 + index)}
                    </span>
                    <span className="text-slate-800">{option}</span>
                  </div>
                </Button>
              </motion.div>
            ))}
          </CardContent>
        </Card>

        {/* 反馈弹窗 - 手动关闭 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-2xl w-full mx-4"
            >
              <Card className={`border-0 shadow-xl ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-6 px-6">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1">
                      <div className="font-semibold mb-3 text-lg">
                        {feedbackCorrect ? '✓ 正确！' : '✗ 错误'}
                      </div>
                      <div className="text-sm opacity-95 leading-relaxed">
                        {feedbackExplanation}
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={handleCloseFeedback}
                      className="text-white hover:bg-white/20 h-8 w-8 p-0 flex-shrink-0"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                  <div className="mt-4 pt-4 border-t border-white/20">
                    <Button
                      onClick={handleCloseFeedback}
                      variant="ghost"
                      className="w-full text-white hover:bg-white/20 font-medium"
                    >
                      {currentQuestion < selectedQuestions.length - 1 ? '下一题' : '查看结果'} →
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalQuestions = selectedQuestions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-yellow-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-yellow-600 to-orange-500 bg-clip-text text-transparent">
              {accuracy}
            </div>
            <p className="text-slate-600">批判性思维准确率</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-xl border border-yellow-200">
                <div className="text-2xl font-bold text-yellow-600 mb-1">{correctAnswers}/{totalQuestions}</div>
                <div className="text-sm text-yellow-700">正确分析</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">{Math.round((Date.now() - startTime) / 60000)}分钟</div>
                <div className="text-sm text-orange-700">用时</div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-yellow-600 to-orange-500 hover:from-yellow-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}